<template>
  <common-layout title="客户管理">
      <template #header-buttons>
        <div class="card-header">
          <el-button type="primary" @click="handleCreate">创建客户</el-button>
        </div>
      </template>

      <template #search-form>
        <el-form :model="searchForm" inline >
          <el-form-item label="客户编码">
            <el-input v-model="searchForm.customerCode" placeholder="请输入客户编码"></el-input>
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input v-model="searchForm.customerName" placeholder="请输入客户名称"></el-input>
          </el-form-item>
          <el-form-item label="客户类型">
            <el-select v-model="searchForm.customerType" placeholder="请选择客户类型">
              <el-option label="全部" value=""></el-option>
              <el-option label="普通客户" value="Normal"></el-option>
              <el-option label="VIP客户" value="VIP"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户状态" >
            <el-select v-model="searchForm.status" placeholder="请选择客户状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="启用" value="Active"></el-option>
              <el-option label="禁用" value="Inactive"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </template>

      <template #data-content>
        <!-- 客户列表 -->
        <el-table v-loading="loading" :data="customerList" style="width: 100%">
          <el-table-column prop="customerCode" label="客户编码" sortable></el-table-column>
          <el-table-column prop="customerName" label="客户名称" sortable></el-table-column>
          <el-table-column prop="customerShortName" label="客户简称"></el-table-column>
          <el-table-column prop="customerType" label="客户类型" sortable>
            <template #default="scope">
              {{ scope.row.customerType === 'Normal' ? '普通客户' : 'VIP客户' }}
            </template>
          </el-table-column>
          <el-table-column prop="contactPerson" label="联系人"></el-table-column>
          <el-table-column prop="contactPhone" label="联系电话"></el-table-column>
          <el-table-column prop="status" label="状态" sortable>
            <template #default="scope">
              <el-tag :type="scope.row.status === 'Active' ? 'success' : 'danger'">{{ scope.row.status === 'Active' ? '启用' : '禁用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" :type="scope.row.status === 'Active' ? 'danger' : 'success'" @click="handleStatusChange(scope.row)">{{ scope.row.status === 'Active' ? '禁用' : '启用' }}</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
        </div>
      </template>
    </common-layout>

    <!-- 客户详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="客户详情" width="70%">
      <el-form :model="currentCustomer" label-width="120px">
        <el-form-item label="客户编码">
          <el-input v-model="currentCustomer.customerCode" disabled></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="currentCustomer.customerName" disabled></el-input>
        </el-form-item>
        <el-form-item label="客户简称">
          <el-input v-model="currentCustomer.customerShortName" disabled></el-input>
        </el-form-item>
        <el-form-item label="客户类型">
          <el-input  :value="currentCustomer.customerType === 'Normal'" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="currentCustomer.contactPerson" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="currentCustomer.contactPhone" disabled></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="currentCustomer.email" disabled></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="currentCustomer.address" disabled></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="currentCustomer.remark" type="textarea" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 创建/编辑客户对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="isEdit ? '编辑客户' : '创建客户'"
      width="70%"
    >
      <el-form
        ref="customerForm"
        :model="formData"
        label-width="120px"
        :rules="formRules"
      >
        <el-form-item label="客户编码" v-if="isEdit">
          <el-input v-model="formData.customerCode" disabled></el-input>
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="formData.customerName" placeholder="请输入客户名称"></el-input>
        </el-form-item>
        <el-form-item label="客户简称" prop="customerShortName">
          <el-input v-model="formData.customerShortName" placeholder="请输入客户简称"></el-input>
        </el-form-item>
        <el-form-item label="客户类型" prop="customerType">
          <el-select v-model="formData.customerType" placeholder="请选择客户类型">
            <el-option label="普通客户" value="Normal"></el-option>
            <el-option label="VIP客户" value="VIP"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="formData.contactPerson" placeholder="请输入联系人"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="formData.contactPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入电子邮箱"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </el-dialog>

    <!-- 状态变更确认对话框 -->
    <el-dialog v-model="statusDialogVisible" title="状态变更确认" width="500px">
      <p>确定要{{ currentCustomer.status === 'Active' ? '禁用' : '启用' }}客户 <strong>{{ currentCustomer.customerName }}</strong> 吗？</p>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmStatusChange">确认</el-button>
      </template>
    </el-dialog>
  
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getCustomers, getCustomer, createCustomer, updateCustomer, updateCustomerStatus } from '@/api/customer';
import CommonLayout from '../components/CommonLayout.vue';

// 组件逻辑从这里开始    // 搜索表单
    const searchForm = reactive({
      customerCode: '',
      customerName: '',
      customerType: '',
      status: ''
    });

    // 客户列表数据
    const customerList = ref([]);
    const loading = ref(false);

    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    });

    // 详情对话框
    const detailDialogVisible = ref(false);
    const currentCustomer = reactive({});

    // 创建/编辑对话框
    const formDialogVisible = ref(false);
    const isEdit = ref(false);
    const formData = reactive({
      customerCode: '',
      customerName: '',
      customerShortName: '',
      customerType: 'Normal',
      contactPerson: '',
      contactPhone: '',
      email: '',
      address: '',
      remark: ''
    });

    // 表单规则
    const formRules = {
      customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
      customerShortName: [{ required: true, message: '请输入客户简称', trigger: 'blur' }],
      customerType: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
      contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
      contactPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
      ],
      email: [
        { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '请输入有效的电子邮箱', trigger: 'blur' }
      ]
    };

    // 状态变更对话框
    const statusDialogVisible = ref(false);

    // 加载客户列表
    const loadCustomerList = async () => {
      loading.value = true;
      try {
        const params = {
          pageNum: pagination.currentPage,
          pageSize: pagination.pageSize,
          keyword: searchForm.customerName || searchForm.customerCode,
          customerType: searchForm.customerType === 'Normal' ,
          status: searchForm.status === 'Active' 
        };
        const response = await getCustomers(params);
        // 映射后端数据到前端期望的格式
        customerList.value = (response?.$values || []).map(customer => ({
          ...customer,
          customerShortName: customer.ShortName,
          status: customer.Status === '启用' ? 'Active' : 'Inactive'
        }));
        pagination.total = response?.totalCount || 0;
      } catch (error) {
        ElMessage.error('获取客户列表失败: ' + (error as Error).message);
        console.error('Failed to load customer list:', error);
      } finally {
        loading.value = false;
      }
    };

    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1;
      loadCustomerList();
    };

    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = '';
      });
      pagination.currentPage = 1;
      loadCustomerList();
    };

    // 分页大小变更
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      loadCustomerList();
    };

    // 当前页码变更
    const handleCurrentChange = (current) => {
      pagination.currentPage = current;
      loadCustomerList();
    };

    // 查看客户详情
    const handleView = async (customer) => {
      loading.value = true;
      try {
        const response = await getCustomer(customer.customerCode);
        Object.assign(currentCustomer, {
          ...response,
          customerShortName: response.ShortName,
          status: response.Status === '启用' ? 'Active' : 'Inactive'
        });
        detailDialogVisible.value = true;
      } catch (error) {
        ElMessage.error('获取客户详情失败: ' + (error as Error).message);
        console.error('Failed to get customer detail:', error);
      } finally {
        loading.value = false;
      }
    };

    // 创建客户
    const handleCreate = () => {
      isEdit.value = false;
      // 重置表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = key === 'customerType' ? 'Normal' : '';
      });
      formDialogVisible.value = true;
    };

    // 编辑客户
    const handleEdit = (customer) => {
      isEdit.value = true;
      Object.assign(formData, customer);
      formDialogVisible.value = true;
    };

    // 提交表单
    const customerForm = ref(null);
    const handleSubmit = async () => {
      try {
        await (customerForm.value as any).validate();
        if (isEdit.value) {
          // 编辑客户
          await updateCustomer(formData.customerCode, formData);
          ElMessage.success('编辑客户成功');
        } else {
          // 创建客户
          await createCustomer(formData);
          ElMessage.success('创建客户成功');
        }
        formDialogVisible.value = false;
        loadCustomerList();
      } catch (error) {
        if ((error as any).name === 'ValidationError') {
          return;
        }
        ElMessage.error(isEdit.value ? '编辑客户失败' : '创建客户失败');
        console.error(isEdit.value ? 'Failed to update customer:' : 'Failed to create customer:', error);
      }
    };

    // 处理状态变更
    const handleStatusChange = (customer) => {
      Object.assign(currentCustomer, customer);
      statusDialogVisible.value = true;
    };

    // 确认状态变更
    const confirmStatusChange = async () => {
      try {
        // 转换前端状态值为后端期望的值
        const newStatus = currentCustomer.status === 'Active' ? '禁用' : '启用';
        await updateCustomerStatus(currentCustomer.customerCode, newStatus);
        ElMessage.success(`客户${currentCustomer.status === 'Active' ? '禁用' : '启用'}成功`);
        statusDialogVisible.value = false;
        loadCustomerList();
      } catch (error) {
        ElMessage.error(`客户${currentCustomer.status === 'Active' ? '禁用' : '启用'}失败`);
        console.error(`Failed to ${currentCustomer.status === 'Active' ? 'disable' : 'enable'} customer:`, error);
      }
    };

    // 初始加载
    onMounted(() => {
      loadCustomerList();
    });

    // 在script setup中不需要return语句
  
</script>

<style scoped>

.customer-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>